// server/app/controller/procurement/purchase_order_controller.js
'use strict';

const Controller = require('egg').Controller;

class PurchaseOrderController extends Controller {
  // 获取采购订单列表
  async index() {
    const { ctx } = this;
    const { page = 1, limit = 10, orderNumber, supplierId, status, startDate, endDate } = ctx.query;
    
    try {
      // 构建查询条件
      const where = {
        organizationId: ctx.state.organizationId
      };
      
      if (orderNumber) {
        where.orderNumber = {
          [ctx.app.Sequelize.Op.like]: `%${orderNumber}%`
        };
      }
      
      if (supplierId) {
        where.supplierId = supplierId;
      }
      
      if (status) {
        where.status = status;
      }
      
      if (startDate || endDate) {
        where.orderDate = {};
        if (startDate) {
          where.orderDate[ctx.app.Sequelize.Op.gte] = new Date(startDate);
        }
        if (endDate) {
          where.orderDate[ctx.app.Sequelize.Op.lte] = new Date(endDate);
        }
      }
      
      // 查询采购订单列表
      const { rows, count } = await ctx.model.PurchaseOrderModel.findAndCountAll({
        where,
        include: [
          {
            model: ctx.model.SupplierModel,
            as: 'supplier',
            attributes: ['id', 'name']
          }
        ],
        order: [['createdAt', 'DESC']],
        limit: parseInt(limit),
        offset: (parseInt(page) - 1) * parseInt(limit)
      });
      
      // 格式化数据
      const list = rows.map(order => ({
        id: order.id,
        orderNumber: order.orderNumber,
        supplierId: order.supplierId,
        supplierName: order.supplier ? order.supplier.name : '',
        purchaser: order.purchaser,
        orderDate: order.orderDate,
        expectedDeliveryDate: order.expectedDeliveryDate,
        totalAmount: order.totalAmount,
        status: order.status,
        remark: order.remark,
        createTime: order.createdAt
      }));
      
      ctx.body = {
        success: true,
        data: {
          list,
          pagination: {
            page: parseInt(page),
            limit: parseInt(limit),
            total: count
          }
        }
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: error.message
      };
    }
  }
  
  // 获取采购订单详情
  async show() {
    const { ctx } = this;
    const { id } = ctx.params;
    
    try {
      const order = await ctx.model.PurchaseOrderModel.findByPk(id, {
        include: [
          {
            model: ctx.model.SupplierModel,
            as: 'supplier',
            attributes: ['id', 'name']
          },
          {
            model: ctx.model.PurchaseOrderItemModel,
            as: 'items',
            attributes: ['id', 'productName', 'specification', 'quantity', 'unit', 'unitPrice', 'amount', 'remark']
          }
        ]
      });
      
      if (!order) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '采购订单不存在'
        };
        return;
      }
      
      // 检查权限
      if (order.organizationId !== ctx.state.organizationId) {
        ctx.status = 403;
        ctx.body = {
          success: false,
          message: '您没有权限访问该采购订单'
        };
        return;
      }
      
      // 格式化数据
      const formattedOrder = {
        id: order.id,
        orderNumber: order.orderNumber,
        supplierId: order.supplierId,
        supplierName: order.supplier ? order.supplier.name : '',
        purchaser: order.purchaser,
        orderDate: order.orderDate,
        expectedDeliveryDate: order.expectedDeliveryDate,
        totalAmount: order.totalAmount,
        status: order.status,
        remark: order.remark,
        createTime: order.createdAt,
        items: order.items.map(item => ({
          id: item.id,
          productName: item.productName,
          specification: item.specification,
          quantity: item.quantity,
          unit: item.unit,
          unitPrice: item.unitPrice,
          amount: item.amount,
          remark: item.remark
        }))
      };
      
      ctx.body = {
        success: true,
        data: formattedOrder
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: error.message
      };
    }
  }
  
  // 创建采购订单
  async create() {
    const { ctx } = this;
    const { orderNumber, supplierId, purchaser, orderDate, expectedDeliveryDate, totalAmount, status, remark, items } = ctx.request.body;
    
    try {
      // 开启事务
      const transaction = await ctx.model.transaction();
      
      try {
        // 创建采购订单
        const order = await ctx.model.PurchaseOrderModel.create({
          orderNumber,
          supplierId,
          purchaser,
          orderDate,
          expectedDeliveryDate,
          totalAmount,
          status: status || 'pending',
          remark,
          organizationId: ctx.state.organizationId
        }, { transaction });
        
        // 创建采购订单项
        if (items && items.length > 0) {
          const orderItems = items.map(item => ({
            orderId: order.id,
            productId: item.productId,
            productName: item.productName,
            specification: item.specification,
            quantity: item.quantity,
            unit: item.unit,
            unitPrice: item.unitPrice,
            amount: item.amount,
            remark: item.remark
          }));
          
          await ctx.model.PurchaseOrderItemModel.bulkCreate(orderItems, { transaction });
        }
        
        // 提交事务
        await transaction.commit();
        
        ctx.status = 201;
        ctx.body = {
          success: true,
          data: {
            id: order.id
          },
          message: '采购订单创建成功'
        };
      } catch (error) {
        // 回滚事务
        await transaction.rollback();
        throw error;
      }
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: error.message
      };
    }
  }
  
  // 更新采购订单
  async update() {
    const { ctx } = this;
    const { id } = ctx.params;
    const { orderNumber, supplierId, purchaser, orderDate, expectedDeliveryDate, totalAmount, status, remark, items } = ctx.request.body;
    
    try {
      const order = await ctx.model.PurchaseOrderModel.findByPk(id);
      
      if (!order) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '采购订单不存在'
        };
        return;
      }
      
      // 检查权限
      if (order.organizationId !== ctx.state.organizationId) {
        ctx.status = 403;
        ctx.body = {
          success: false,
          message: '您没有权限修改该采购订单'
        };
        return;
      }
      
      // 开启事务
      const transaction = await ctx.model.transaction();
      
      try {
        // 更新采购订单
        await order.update({
          orderNumber,
          supplierId,
          purchaser,
          orderDate,
          expectedDeliveryDate,
          totalAmount,
          status,
          remark
        }, { transaction });
        
        // 更新采购订单项（先删除再重新创建）
        if (items && items.length > 0) {
          await ctx.model.PurchaseOrderItemModel.destroy({
            where: { orderId: id }
          }, { transaction });
          
          const orderItems = items.map(item => ({
            orderId: order.id,
            productId: item.productId,
            productName: item.productName,
            specification: item.specification,
            quantity: item.quantity,
            unit: item.unit,
            unitPrice: item.unitPrice,
            amount: item.amount,
            remark: item.remark
          }));
          
          await ctx.model.PurchaseOrderItemModel.bulkCreate(orderItems, { transaction });
        }
        
        // 提交事务
        await transaction.commit();
        
        ctx.body = {
          success: true,
          message: '采购订单更新成功'
        };
      } catch (error) {
        // 回滚事务
        await transaction.rollback();
        throw error;
      }
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: error.message
      };
    }
  }
  
  // 删除采购订单
  async destroy() {
    const { ctx } = this;
    const { id } = ctx.params;
    
    try {
      const order = await ctx.model.PurchaseOrderModel.findByPk(id);
      
      if (!order) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '采购订单不存在'
        };
        return;
      }
      
      // 检查权限
      if (order.organizationId !== ctx.state.organizationId) {
        ctx.status = 403;
        ctx.body = {
          success: false,
          message: '您没有权限删除该采购订单'
        };
        return;
      }
      
      // 开启事务
      const transaction = await ctx.model.transaction();
      
      try {
        // 删除采购订单项
        await ctx.model.PurchaseOrderItemModel.destroy({
          where: { orderId: id }
        }, { transaction });
        
        // 删除采购订单
        await order.destroy({ transaction });
        
        // 提交事务
        await transaction.commit();
        
        ctx.body = {
          success: true,
          message: '采购订单删除成功'
        };
      } catch (error) {
        // 回滚事务
        await transaction.rollback();
        throw error;
      }
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: error.message
      };
    }
  }
  
  // 获取统计信息
  async stats() {
    const { ctx } = this;
    
    try {
      const stats = await ctx.model.PurchaseOrderModel.findAll({
        where: {
          organizationId: ctx.state.organizationId
        },
        attributes: [
          'status',
          [ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count'],
          [ctx.app.Sequelize.fn('SUM', ctx.app.Sequelize.col('total_amount')), 'totalAmount']
        ],
        group: ['status']
      });
      
      // 格式化统计数据
      const result = {
        totalOrders: 0,
        pendingOrders: 0,
        completedOrders: 0,
        monthlyAmount: 0,
        supplierCount: 0
      };
      
      stats.forEach(item => {
        const status = item.status;
        const count = parseInt(item.getDataValue('count'));
        const totalAmount = parseFloat(item.getDataValue('totalAmount')) || 0;
        
        result.totalOrders += count;
        
        if (status === 'pending') {
          result.pendingOrders = count;
        } else if (status === 'completed') {
          result.completedOrders = count;
        }
        
        result.monthlyAmount += totalAmount;
      });
      
      // 获取供应商数量
      const supplierCount = await ctx.model.SupplierModel.count({
        where: {
          organizationId: ctx.state.organizationId
        }
      });
      
      result.supplierCount = supplierCount;
      
      ctx.body = {
        success: true,
        data: result
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: error.message
      };
    }
  }
}

module.exports = PurchaseOrderController;